const { generateUUID } = require('../utils')
const moment = require('moment');
const fs = require('fs');
const { folderExists, createFolder, createFile, readFile, writeFile } = require('./file')
const { RESULT } = require('../config/index')

// 初始化数据库
const initObject = (cb) => {
  folderExists('database', (exists) => {
    if (exists) {
      RESULT.status = 5003;
      RESULT.message = '项目已经初始化'
      cb(RESULT)
    } else {
      createFolder('database', (err) => {
        if (err) throw err
        createFile('t_object', [], (err) => {
          if (err) throw err
          RESULT.message = '项目初始化完成'
          cb(RESULT)
        })
      })
    }
  })
}
// 添加表
const addCollection = (body, cb) => {
  const { tableValue } = body;
  readFile('t_object', (res) => {
    let obj = res.find(x => x.tableValue === tableValue)
    if (obj) {
      RESULT.status = 4001;
      RESULT.message = '表名已存在'
      cb(RESULT)
    } else {
      createFile(tableValue, [], (err) => {
        if (err) {
          RESULT.status = 5001;
          RESULT.message = '创建失败'
        }
        cb(RESULT)
        addCollectionDetails(body)
      })
    }
  })
}

// 添加表详情
const addCollectionDetails = (body) => {
  const { tableName, tableValue } = body
  let data = {
    _id: generateUUID(),
    tableName,
    tableValue,
    ctime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),//创建时间
    fieldList: []
  }
  readFile('t_object', (res) => {
    res.push(data)
    writeFile('t_object', res, (err) => {
      if (err) throw new Error(err)
    })
  })
}

// 添加数据到表中(一条)
const addDataToCollection = (tableValue, data, cb) => {
  readFile(tableValue, (res) => {
    data._id = generateUUID()
    data.ctime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");// 创建时间
    res.push(data)
    console.log(res)
    writeFile(tableValue, res, (err) => {
      if (err) {
        RESULT.status = 5002
        RESULT.message = '添加失败'
      }
      cb(RESULT)
    })
  })
}

// 添加表字段
const addField = function () {
  // let ctime = moment(new Date()).format("YYYY-MM-DD");
}

exports.initObject = initObject;
exports.addCollection = addCollection;
exports.addDataToCollection = addDataToCollection;